import {createRouter,createWebHistory} from 'vue-router'
import UserHome from '@/pages/UserHome.vue'
import UserLogin from '@/pages/UserLogin.vue';
import UserAccess from '@/pages/UserAccess.vue';
import UserManager from '@/pages/UserManager.vue';
import UserMachine from '@/pages/UserMachine.vue';
import UserAnaylze from '@/pages/UserAnaylze.vue';
import UserMap from '@/pages/UserMap.vue';
import UserOrders from '@/pages/UserOrders.vue';
import UserArea from '@/pages/UserArea.vue';
import UserNoAccess from '@/pages/UserNoAccess.vue';
import isTokenValid from '@/utils/auth';
import axiosInstance from '@/utils/axios';


const routes = [
    {
        path: '',
        component: () => UserHome
    },
    {
        name: 'home',
        path: '/home',
        component: () => UserHome,
        children:[
            {
                name: 'access',
                path: '/access',
                component: () => UserAccess
            },
            {
                name: 'user',
                path: '/user',
                component: () => UserManager
            },
            {
                name: 'machine',
                path: '/machine',
                component: () => UserMachine
            },
            {
                name: 'orders',
                path: '/orders',
                component: () => UserOrders
            },
            {
                name: 'anaylze',
                path: '/anaylze',
                component: () => UserAnaylze
            },
            {
                name: 'map',
                path: '/map',
                component: () => UserMap
            },
            {
                name: 'area',
                path: '/area',
                component: () => UserArea
            }
        ]
    },
    {
        name: 'login',
        path: '/login',
        component: () => UserLogin
    },
    {
        name: 'ununauthorized',
        path:'/unauthorized',
        component: () => UserNoAccess
    }
    
];

const router = createRouter({
    history: createWebHistory(),
    routes,
  });

  router.beforeEach(async (to, from, next) => {
    const token_str = window.sessionStorage.getItem('token') || window.localStorage.getItem('token');
    
    // 如果已经登录且访问的是 login 路由，则跳转到 home
    if (token_str && to.path === '/login') {
        return next('/home');  // 已登录用户跳回 home 页面
    }

    if (to.path === '/') {
        return next('/login')  // 根路径跳转到 login 页面
    }

    if (to.path === '/login' || to.path === '/unauthorized') {
        return next();  // 直接允许进入 login 或 unauthorized 路由
    }
    
    // 如果没有 token，重定向到登录页面
    if (!token_str) {
        alert("请先登录");
        return next('/login');
    }

    // 检验 token 是否有效
    if (isTokenValid(token_str)) {
        try {
            // 去掉斜杠
            const path = to.path.replace(/\//g, ''); 

            // 调用后端接口校验权限
            const response = await axiosInstance.get('/api/verify_menu_permission', {
                params: { path },
            });

            if (response.data.success) {
                return next(); 
            } 
            else {
                alert("你无权访问")
                return next('/unauthorized')
            }
        } catch (error) {
            console.error("权限校验失败", error);
            alert("服务异常，请稍后再试");
            return next('/login'); // 出现异常时跳转登录
        }
    } else {
        // 如果 token 无效或已过期，清除 token 并重定向到登录页面
        alert("登录已过期，请重新登录");
        window.sessionStorage.removeItem('token');
        window.localStorage.removeItem('token');
        return next('/login');
    }

    
});

  
  export default router;